{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Use GLM-4 Models in Microsoft TaskWeaver Framework\n",
    "\n",
    "**This tutorial is available in English and is attached below the Chinese explanation**\n",
    "\n",
    "\n",
    "TaskWeaver 是一个代码优先的 Agent 框架，用于无缝规划和执行数据分析任务。这种创新框架通过代码片段解释用户请求，并以函数的形式有效协调各种插件，以有状态的方式执行数据分析任务。\n",
    "本代码将使用 微软的 TaskWeaver 框架，并使用 GLM-4 模型来完成具有规划性的 Agent 任务。\n",
    "\n",
    "TaskWeaver is a code-first Agent framework for seamlessly planning and executing data analysis tasks. This innovative framework interprets user requests through code snippets and effectively coordinates various plug-ins in the form of functions to perform data analysis tasks in a stateful manner.\n",
    "This code will use Microsoft's TaskWeaver framework and use the GLM-4 model to complete planned Agent tasks."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "e85ef3cfd6a394ab"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Install TaskWeaver\n",
    "\n",
    "请注意，本 cookbook 需要在 TaskWeaver 仓库内运行，基础上进行修改，因此，我们需要先安装 TaskWeaver，你可以按照[官方方案](https://microsoft.github.io/TaskWeaver/docs/experience) 进行安装。\n",
    "\n",
    "Please note that this cookbook needs to be run in the TaskWeaver warehouse and modified based on it. Therefore, we need to install TaskWeaver first. You can follow the [official plan](https://microsoft.github.io/TaskWeaver/docs/experience) Install.\n",
    "\n",
    "```shell\n",
    "git clone https://github.com/microsoft/TaskWeaver.git\n",
    "cd TaskWeaver\n",
    "# install the requirements\n",
    "pip install -r requirements.txt\n",
    "```"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "df0d1026c65664bf"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Config GLM-4 Model in TaskWeaver\n",
    "接着，只需要修改 `project/taskweaver_config.json` 中的相关配置，按照[官方文档](https://microsoft.github.io/TaskWeaver/docs/llms/glm) 进行配置，即可使用 GLM-4 模型作为模型底座。\n",
    "\n",
    "Then, you only need to modify the relevant configurations in `project/taskweaver_config.json` and configure according to [official documentation](https://microsoft.github.io/TaskWeaver/docs/llms/glm) to use GLM-4 The model serves as a model base.\n",
    "\n",
    "```json\n",
    "{\n",
    "  \"llm.api_base\": \"https://open.bigmodel.cn/api/paas/v4\",\n",
    "  \"llm.api_key\": \"your keys\",\n",
    "  \"llm.api_type\": \"zhipuai\",\n",
    "  \"llm.model\": \"glm-4\",\n",
    "  \"llm.embedding_model\": \"embedding-2\",\n",
    "  \"llm.embedding_api_type\": \"zhipuai\"\n",
    "}\n",
    "```"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "e088fff610aed3cd"
  },
  {
   "cell_type": "markdown",
   "source": [
    "使用 `taskweaver` 命令来启动 TaskWeaver 服务，同时，我们执行[官方示例](https://microsoft.github.io/TaskWeaver/docs/experience) 来验证 GLM-4 的规划和执行能力。\n",
    "\n",
    "Use the `taskweaver` command to start the TaskWeaver service. At the same time, we execute [official example](https://microsoft.github.io/TaskWeaver/docs/experience) to verify the planning and execution capabilities of GLM-4."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "f8e64d596f62f8fb"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "!python -m taskweaver -p ./project/"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "62b683ce1eee7f18"
  },
  {
   "cell_type": "markdown",
   "source": [
    "``````\n",
    "=========================================================\n",
    " _____         _     _       __\n",
    "|_   _|_ _ ___| | _ | |     / /__  ____ __   _____  _____\n",
    "  | |/ _` / __| |/ /| | /| / / _ \\/ __ `/ | / / _ \\/ ___/\n",
    "  | | (_| \\__ \\   < | |/ |/ /  __/ /_/ /| |/ /  __/ /\n",
    "  |_|\\__,_|___/_|\\_\\|__/|__/\\___/\\__,_/ |___/\\___/_/\n",
    "=========================================================\n",
    " TaskWeaver ▶  I am TaskWeaver, an AI assistant. To get started, could you please enter your request?\n",
    "    Human   ▶  calculate the mean value of ./project/sample_data/demo_data.csv\n",
    " ╭───< Planner >\n",
    " ├─► [init_plan]\n",
    " │   1. Load the demo_data.csv file\n",
    " │   2. Calculate the mean value of the loaded data <sequentially depends on 1>\n",
    " │   3. Report the result to the user <interactively depends on 2>\n",
    " ├─► [plan]\n",
    " │   1. Instruct CodeInterpreter to load the demo_data.csv file and calculate the mean value\n",
    " │   2. Report the result to the user\n",
    " ├─► [current_plan_step] 1. Instruct CodeInterpreter to load the demo_data.csv file and calculate the mean value\n",
    " ├──● Please load the demo_data.csv file from ./project/sample_data/ and calculate the mean value of the loaded data\n",
    " ╰──● sending message to CodeInterpreter\n",
    " ╭───< CodeInterpreter >\n",
    " ├─► [thought] ProgramApe will generate a code snippet to load the demo_data.csv file and calculate the mean value of the data.\n",
    " ├─► [python]\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean().mean()\n",
    " │   mean_value\n",
    " ├─► [verification] NONE\n",
    " ├─► [code_error] No code verification is performed.\n",
    "0.00s - Debugger warning: It seems that frozen modules are being used, which may\n",
    "0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off\n",
    "0.00s - to python to disable frozen modules.\n",
    "0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.\n",
    " ├─► [execution_status] FAILURE\n",
    " ├─► [execution_result]\n",
    " │   The execution of the generated python code above has failed\n",
    " │   \n",
    " │   During execution, the following messages were logged:\n",
    " │   Traceback (most recent call last):\n",
    " │   \n",
    " │     Cell In[1], line 6\n",
    " │       mean_value = df.mean().mean()\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11666 in mean\n",
    " │       result = super().mean(axis, skipna, numeric_only, **kwargs)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12413 in mean\n",
    " │       return self._stat_function(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12370 in _stat_function\n",
    " │       return self._reduce(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11535 in _reduce\n",
    " │       res = df._mgr.reduce(blk_func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/managers.py:1501 in reduce\n",
    " │       nbs = blk.reduce(func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/blocks.py:404 in reduce\n",
    " │       result = func(self.values)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11\n",
    " │   \n",
    " ├─► [artifact_paths] []\n",
    " ├──● The following python code has been executed:\n",
    " │   ```python\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean().mean()\n",
    " │   mean_value\n",
    " │   ```\n",
    " │   \n",
    " │   \n",
    " │   The execution of the generated python code above has failed\n",
    " │   \n",
    " │   During execution, the following messages were logged:\n",
    " │   Traceback (most recent call last):\n",
    " │   \n",
    " │     Cell In[1], line 6\n",
    " │       mean_value = df.mean().mean()\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11666 in mean\n",
    " │       result = super().mean(axis, skipna, numeric_only, **kwargs)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12413 in mean\n",
    " │       return self._stat_function(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12370 in _stat_function\n",
    " │       return self._reduce(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11535 in _reduce\n",
    " │       res = df._mgr.reduce(blk_func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/managers.py:1501 in reduce\n",
    " │       nbs = blk.reduce(func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/blocks.py:404 in reduce\n",
    " │       result = func(self.values)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11\n",
    " │   \n",
    " ├─► [revise_message]\n",
    " │   The execution of the previous generated code has failed. If you think you can fix the problem by rewriting the code, please generate code and run it again.\n",
    " │   Otherwise, please explain the problem to me.\n",
    " ╰──● sending message to CodeInterpreter\n",
    " ╭───< CodeInterpreter >\n",
    " ├─► [thought] The previous code failed because it attempted to calculate the mean of the mean, which is not the intended operation. ProgramApe will correct this by calculating the mean of the \n",
    " │   entire DataFrame.\n",
    " ├─► [python]\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean()\n",
    " │   mean_value\n",
    " ├─► [verification] NONE\n",
    " ├─► [code_error] No code verification is performed.\n",
    " ├─► [execution_status] FAILURE\n",
    " ├─► [execution_result]\n",
    " │   The execution of the generated python code above has failed\n",
    " │   \n",
    " │   During execution, the following messages were logged:\n",
    " │   Traceback (most recent call last):\n",
    " │   \n",
    " │     Cell In[2], line 6\n",
    " │       mean_value = df.mean()\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11666 in mean\n",
    " │       result = super().mean(axis, skipna, numeric_only, **kwargs)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12413 in mean\n",
    " │       return self._stat_function(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12370 in _stat_function\n",
    " │       return self._reduce(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11535 in _reduce\n",
    " │       res = df._mgr.reduce(blk_func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/managers.py:1501 in reduce\n",
    " │       nbs = blk.reduce(func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/blocks.py:404 in reduce\n",
    " │       result = func(self.values)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11454 in \n",
    " │   \n",
    " ├─► [artifact_paths] []\n",
    " ├──● The following python code has been executed:\n",
    " │   ```python\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean()\n",
    " │   mean_value\n",
    " │   ```\n",
    " │   \n",
    " │   \n",
    " │   The execution of the generated python code above has failed\n",
    " │   \n",
    " │   During execution, the following messages were logged:\n",
    " │   Traceback (most recent call last):\n",
    " │   \n",
    " │     Cell In[2], line 6\n",
    " │       mean_value = df.mean()\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11666 in mean\n",
    " │       result = super().mean(axis, skipna, numeric_only, **kwargs)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12413 in mean\n",
    " │       return self._stat_function(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/generic.py:12370 in _stat_function\n",
    " │       return self._reduce(\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11535 in _reduce\n",
    " │       res = df._mgr.reduce(blk_func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/managers.py:1501 in reduce\n",
    " │       nbs = blk.reduce(func)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/internals/blocks.py:404 in reduce\n",
    " │       result = func(self.values)\n",
    " │   \n",
    " │     File ~/Code/TaskWeaver/venv/lib/python3.12/site-packages/pandas/core/frame.py:11454 in \n",
    " │   \n",
    " ├─► [revise_message]\n",
    " │   The execution of the previous generated code has failed. If you think you can fix the problem by rewriting the code, please generate code and run it again.\n",
    " │   Otherwise, please explain the problem to me.\n",
    " ╰──● sending message to CodeInterpreter\n",
    " ╭───< CodeInterpreter >\n",
    " ├─► [thought] ProgramApe understands the new instructions and will follow them to correct the code. The previous failure was due to an attempt to calculate the mean of the entire DataFrame without \n",
    " │   specifying an axis, which caused an ambiguity. ProgramApe will now calculate the mean of the numeric columns only.\n",
    " ├─► [python]\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean(numeric_only=True)\n",
    " │   mean_value\n",
    " ├─► [verification] NONE\n",
    " ├─► [code_error] No code verification is performed.\n",
    " ├─► [execution_status] SUCCESS\n",
    " ├─► [execution_result]\n",
    " │   The execution of the generated python code above has succeeded\n",
    " │   \n",
    " │   The result of above Python code after execution is:\n",
    " │   Count    78172.75\n",
    " │   dtype: float64\n",
    " ├─► [artifact_paths] []\n",
    " ├──● The following python code has been executed:\n",
    " │   ```python\n",
    " │   import pandas as pd\n",
    " │   \n",
    " │   file_path = \"./project/sample_data/demo_data.csv\"\n",
    " │   \n",
    " │   df = pd.read_csv(file_path)\n",
    " │   mean_value = df.mean(numeric_only=True)\n",
    " │   mean_value\n",
    " │   ```\n",
    " │   \n",
    " │   \n",
    " │   The execution of the generated python code above has succeeded\n",
    " │   \n",
    " │   The result of above Python code after execution is:\n",
    " │   Count    78172.75\n",
    " │   dtype: float64\n",
    " ╰──● sending message to Planner\n",
    " ╭───< Planner >\n",
    " ├─► [init_plan]\n",
    " │   1. Load the demo_data.csv file\n",
    " │   2. Calculate the mean value of the loaded data <sequentially depends on 1>\n",
    " │   3. Report the result to the user <interactively depends on 2>\n",
    " ├─► [plan]\n",
    " │   1. Instruct CodeInterpreter to load the demo_data.csv file and calculate the mean value\n",
    " │   2. Report the result to the user\n",
    " ├─► [current_plan_step] 2. Report the result to the user\n",
    " ├──● The mean value of the data in demo_data.csv is 78172.75\n",
    " ╰──● sending message to User\n",
    " TaskWeaver ▶  The mean value of the data in demo_data.csv is 78172.75\n",
    " ``````"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "87d45c02643b3aed"
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Conclusion\n",
    "\n",
    "在示例中， GLM-4同样计算出了正确答案，虽然相较于 GPT-4 尝试了更多字数\n",
    "GLM-4 模型非常能够规划和执行任务，我们可以通过 TaskWeaver 框架使用 GLM-4 模型完成更多任务。\n",
    "\n",
    "The GLM-4 model is very capable of planning and executing tasks. Although it tried more words than GPT-4, it also calculated the correct answer in the example.We can use the GLM-4 model through the TaskWeaver framework to complete more tasks."
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "6c60402b7dda1f34"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
